<?php

class ScriptAlone_Store_File extends ScriptAlone_Store {

	protected $filepath;

	public function __construct($filepath) {
		if(!is_writable(dirname($filepath)) || (is_file($filepath) && !is_writable($filepath))) {
			throw new Exception('File "' . $filepath . '" is not writable');
		}
		$this->filepath = $filepath;
	}

	protected function parseStateData($string) {
		$vars = array();
		if(preg_match_all('/([\w]+?)\:\s*(.+)/', $string, $m)) {
			foreach($m[1] as $i => $title) {
				$vars[$title] = $m[2][$i];
			}
		}
		return $vars;
	}

	protected function buildStateData(array $vars) {
		$data = '';
		foreach($vars as $title => $value) {
			$data .= "$title: $value\n";
		}
		return rtrim($data, "\n");
	}

	/**
	 * @return ScriptAlone_State|null
	 */
	public function getState() {
		if(is_file($this->filepath)) {
			$stateString = file_get_contents($this->filepath);
			if(!$stateString) {
				throw new Exception('Unable to read file "' . $this->filepath . '"');
			}
			$stateData = $this->parseStateData($stateString);
			return new ScriptAlone_State($stateData['Status'], $stateData['PID'], strtotime($stateData['Started']), strtotime($stateData['Worked']), strtotime($stateData['Expire']));
		}
	}

	/**
	 * @param ScriptAlone_State $state
	 * @throws Exception
	 */
	public function saveState(ScriptAlone_State $state) {
		$stateString = $this->buildStateData(array(
				'Status' => $state->status,
				'PID' => $state->pid,
				'Started' => date('Y-m-d H:i:s', $state->started),
				'Worked' => date('Y-m-d H:i:s', $state->worked),
				'Expire' => date('Y-m-d H:i:s', $state->expire))
		);
		if(!file_put_contents($this->filepath, $stateString)) {
			throw new Exception('Saving state was failed, cannot write file ' . $this->filepath);
		}
	}

	public function clearState() {
		if(is_file($this->filepath)) {
			unlink($this->filepath);
		}
	}
}
